#include "StdAfx.h"

#include "ColorUtils/Color.h"
#include "ColorUtils/Image.h"

#include "FirstIntersectionResult.h"
#include "SecondIntersectionResult.h"
#include "FlatRectangle.h"

#include "TexturedRectangle.h"


TexturedRectangle::TexturedRectangle(Point p0, Point p1, Point p2, const Image_ptr  textureImage) : FlatRectangle(p0, p1, p2, Point(0, 0, 0)), _image(textureImage)
{}

void TexturedRectangle::ColorAtIntersection(SecondIntersectionResult& result, const Point& point, const Ray&)
{
	double temp1, temp2;

	if (_zOfNormal != 0)
		temp1 = ((point.X - _p0.X) * _vec2.Y - (point.Y - _p0.Y) * _vec2.X) / _zOfNormal;
	else if (_yOfNormal != 0)
		temp1 = ((point.Z - _p0.Z) * _vec2.X - (point.X - _p0.X) * _vec2.Z) / _yOfNormal;
	else
		temp1 = ((point.Y - _p0.Y) * _vec2.Z - (point.Z - _p0.Z) * _vec2.Y) / _xOfNormal;

	if (_zOfNormal != 0)
		temp2 = ((point.Y - _p0.Y) * _vec1.X - (point.X - _p0.X) * _vec1.Y) / _zOfNormal;
	else if (_yOfNormal != 0)
		temp2 = ((point.X - _p0.X) * _vec1.Z - (point.Z - _p0.Z) * _vec1.X) / _yOfNormal;
	else
		temp2 = ((point.Z - _p0.Z) * _vec1.Y - (point.Y - _p0.Y) * _vec1.Z) / _xOfNormal;

	if  (temp1 < 0)
		temp1 = 0;
	if (temp2 < 0)
		temp2 = 0;

	result.ColorAtPoint = _image->GetColor(temp1 * _image->Width(), temp2 * _image->Height());
}
